package com.zzyl.framework.interceptor;

import ch.qos.logback.classic.turbo.TurboFilter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.tokenizer.TokenizerUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import okhttp3.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是controller层的代码
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        //获取token
        String token = request.getHeader("authorization");
        //判断token是否位null
        if(StringUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //解析token 失败就抛异常
        Claims claims;
        try {
             claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //判断数据是否为null
        if(ObjectUtil.isEmpty(claims))
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //获取claims中的userId数据
        Long userId = Long.valueOf(claims.get("userId").toString()) ;
        if(ObjectUtil.isEmpty(userId))
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //将数据userId存到ThreadLocal中
        UserThreadLocal.set(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //全部程序结束之后将UserThreadLocal清空
        UserThreadLocal.remove();
    }
}
